import grails.util.Environment
import com.grailsinaction.*


class BootStrap {

    def init = { servletContext ->
        switch (Environment.current) {
            case Environment.DEVELOPMENT:
                createTestUser('admin', 'secret', '', 'admin@yourhost.com', '')
                createTestUsers()
                break;
            case Environment.PRODUCTION:
                println("No special configuration required")
                break;
        }
    }

    def destroy = {
    }

    void createTestUsers() {
        createTestUser("cnorris", "kickme", "Chuck Norris", "c@n.com", "http://www.chucknorrisfacts.com")
        createTestUser("jackiec", "drunken", "Jackie Chan", "j@c.com", "http://www.imdb.com")
        createTestUser("vandamaj", "bldsprt", "JC VanDamme", "jc@vd.com", "http://www.reddit.com")
        createTestUser("dragonb", "nchucks", "Bruce Lee", "bl@kungfu.com", "http://www.zombo.com")
    }

    void createTestUser(String userId, String password, String fullName, String email, String homepage) {
        if (!User.findByUserId(userId)) {
            println("No ${userId} found.  Creating ${userId} user.")
            def profile = new Profile(fullName: fullName, email: email, homepage: homepage)
            def user = new User(userId: userId, password: password, profile: profile).save()
            if (user) {
                createTestPosts(user)
            } else {
                println("we have a problem")
            }
        } else {
            println("Existing ${userId} in database, skipping creation")
        }
    }

    void createTestPosts(User user) {
        if (user.profile.fullName) {
            def name = user.profile.fullName
            def post1 = new Post(content: "${name} likes it.")
            def post2 = new Post(content: "${name} likes his chicken spicy.")
            addPostToUser(post1, user)
            addPostToUser(post2, user)
        } else {
            println("   -not making posts.")
        }
    }

    void addPostToUser(post, user) {
        if (post) {
            user.addToPosts(post)
        } else {
            println("  -problem with post")
        }
    }

}